// https://www.lintcode.com/problem/text-compression/

public class Solution {
    /**
     * @param lines: the text to compress.
     * @return: return the text after compression.
     */
    public String[] textCompression(String[] lines) {
        // write your code here.
        String[] ret = new String[lines.length];
        Map<String, Integer> map = new HashMap<>();
        Integer pos = 1;
        for (int i = 0; i < lines.length; ++i) {
            String line = lines[i];
            StringBuilder _ret = new StringBuilder();
            StringBuilder word = new StringBuilder();
            for (int j = 0; j < line.length(); ++j) {
                Character c = line.charAt(j);
                if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'))) {
                    word.append(c);
                } else {
                    if (word.length() > 0) {
                        String _word = word.toString();
                        if (map.containsKey(_word)) {
                            _ret.append(Integer.toString(map.get(_word)));
                        } else {
                            _ret.append(_word);
                            map.put(_word, pos);
                            ++pos;
                        }
                        word.delete(0, word.length());
                    }
                    _ret.append(c);
                }
            }
            if (word.length() > 0) {
                String _word = word.toString();
                if (map.containsKey(_word)) {
                    _ret.append(Integer.toString(map.get(_word)));
                } else {
                    _ret.append(_word);
                    map.put(_word, pos);
                    ++pos;
                }
            }
            ret[i] = _ret.toString();
        }
        return ret;
    }
}